package exam.demo1;

class Solution
{
    int m, n;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    boolean[][] vis;
    char[] word;
    public boolean exist (String[] board, String _word)
    {
        m = board.length;
        n = board[0].length();
        vis = new boolean[m][n];
        word = _word.toCharArray();
        // 在 board[i][j] 每一个位置都调用 dfs 函数判断;
        // 只要一个为 true, 则表明至少有一条路可以走, 则返回 true;
        // 若为 false, 则继续判断下一个位置，直到所有位置都没有路，最后返回 false;
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(board[i].charAt(j) == word[0])
                {
                    if(dfs(board, i, j, 0) == true)
                        return true;
                }
            }
        }
        return false;
    }

    // 判断是否可以走完一条
    public boolean dfs(String[] board, int i, int j, int pos)
    {
        // pos=0, word里面没有单词
        if(pos == word.length - 1)
        {
            return true;
        }

        vis[i][j] = true;
        for(int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && board[x].charAt(y) == word[pos + 1])
            {
                if(dfs(board, x, y, pos + 1)) return true;
            }
        }
        vis[i][j] = false;

        return false;
    }
}

public class Test1 {

    public static void main(String[] args) {
        Solution solution = new Solution();

        String[] board = {"XYZE","SFZS","XDEE"};
        String word1 = "XYZZED";
        String word2 = "SEE";
        String word3 = "XYZY";
        boolean a = solution.exist(board, word1);
        boolean b = solution.exist(board, word2);
        boolean c = solution.exist(board, word3);
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}
